<template>
  <div class="books-page">
    <div class="container">
      <div class="header">
        <h1 class="title">📚 我的单词书</h1>
        <div class="actions">
          <button class="btn btn-secondary" @click="refreshBooks">刷新</button>
          <button class="btn btn-primary" @click="goHome">返回首页</button>
        </div>
      </div>

      <div v-if="loading" class="loading">
        <div class="loading-spinner"></div>
        <p>正在加载单词书...</p>
      </div>

      <div v-else-if="error" class="error-message card">
        <h3>⚠️ 加载失败</h3>
        <p>{{ error }}</p>
        <button class="btn btn-primary mt-3" @click="loadBooks">重试</button>
      </div>

      <div v-else-if="books.length === 0" class="empty-state card">
        <div class="empty-icon">📖</div>
        <h3>暂无单词书</h3>
        <p>请先在扇贝官网添加单词书</p>
      </div>

      <div v-else class="books-grid">
        <div v-for="book in books" :key="book.materialbook.id" class="book-card card">
          <div class="book-cover">
            <img
              v-if="book.materialbook.icon_url"
              :src="book.materialbook.icon_url"
              :alt="book.materialbook.name"
            />
            <div v-else class="default-cover">📚</div>
          </div>

          <div class="book-info">
            <h3 class="book-title">{{ book.materialbook.name }}</h3>
            <p class="book-description">{{ book.materialbook.description }}</p>
            <div class="book-progress">
              <div class="progress-bar">
                <div class="progress-fill" :style="{ width: `${getProgress(book)}%` }"></div>
              </div>
              <span class="progress-text">
                {{ book.finished_count || 0 }}/{{ book.materialbook.total_count || 0 }} 词
              </span>
            </div>

            <div class="book-actions">
              <button
                class="btn btn-primary"
                @click="startStudy(book)"
                :disabled="isAllLearned(book)"
              >
                {{ isAllLearned(book) ? '已全部学完' : '开始学习' }}
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { getBookShelf, type BookDetail } from '@/api/scallop'
import { useRouter } from 'vue-router'
import Cookies from 'js-cookie'

const router = useRouter()

const books = ref<BookDetail[]>([])
const loading = ref(false)
const error = ref('')

onMounted(() => {
  // 检查是否有 token
  const token = Cookies.get('auth_token')
  if (!token) {
    router.push('/')
    return
  }
  loadBooks()
})

const loadBooks = async () => {
  loading.value = true
  error.value = ''

  try {
    // 调用模拟 API
    const response = await getBookShelf()
    books.value = response.objects || []
    console.log(books.value)
  } catch (err: any) {
    console.error('加载单词书失败:', err)
    error.value = err.response?.data?.message || '网络请求失败，请检查登录状态'

    // 如果是认证错误，跳转回首页
    if (err.response?.status === 401) {
      Cookies.remove('auth_token')
      router.push('/')
    }
  } finally {
    loading.value = false
  }
}

const refreshBooks = () => {
  loadBooks()
}

const goHome = () => {
  router.push('/')
}

// 计算学习进度百分比
const getProgress = (book: BookDetail) => {
  if (!book.materialbook.total_count) return 0
  return Math.round((book.finished_count / book.materialbook.total_count) * 100)
}

// 判断是否已全部学完
const isAllLearned = (book: BookDetail) => {
  return book.finished_count >= book.materialbook.total_count
}

// 开始学习
const startStudy = (book: BookDetail) => {
  router.push(`/study/${book.materialbook.id}`)
}
</script>

<style scoped lang="scss">
.books-page {
  min-height: 100vh;
  padding: 40px 0;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 40px;
    flex-wrap: wrap;
    gap: 20px;

    .title {
      font-size: 2rem;
      font-weight: 700;
      color: var(--primary-color);
    }

    .actions {
      display: flex;
      gap: 12px;
    }
  }

  .loading {
    text-align: center;
    padding: 60px 20px;

    .loading-spinner {
      width: 40px;
      height: 40px;
      border: 4px solid var(--border-color);
      border-left: 4px solid var(--primary-color);
      border-radius: 50%;
      animation: spin 1s linear infinite;
      margin: 0 auto 20px;
    }

    p {
      color: var(--text-secondary);
      font-size: 1.1rem;
    }
  }

  .error-message {
    text-align: center;
    max-width: 500px;
    margin: 60px auto;

    h3 {
      color: #d32f2f;
      margin-bottom: 12px;
    }

    p {
      color: var(--text-secondary);
      line-height: 1.5;
    }
  }

  .empty-state {
    text-align: center;
    max-width: 400px;
    margin: 60px auto;

    .empty-icon {
      font-size: 4rem;
      margin-bottom: 20px;
    }

    h3 {
      color: var(--text-primary);
      margin-bottom: 12px;
    }

    p {
      color: var(--text-secondary);
    }
  }

  .books-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
    gap: 24px;

    .book-card {
      display: flex;
      flex-direction: column;
      height: 100%;

      .book-cover {
        margin: 0 auto;
        width: 200px;
        height: 280px;
        overflow: hidden;
        border-radius: 8px;
        margin-bottom: 16px;
        background: var(--background-light);
        display: flex;
        align-items: center;
        justify-content: center;

        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }

        .default-cover {
          font-size: 4rem;
          color: var(--primary-color);
        }
      }

      .book-info {
        flex: 1;
        display: flex;
        flex-direction: column;

        .book-title {
          font-size: 1.2rem;
          font-weight: 600;
          color: var(--text-primary);
          margin-bottom: 8px;
          line-height: 1.4;
        }

        .book-description {
          font-size: 0.9rem;
          color: var(--text-secondary);
          line-height: 1.4;
          margin-bottom: 16px;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          line-clamp: 2;
          -webkit-box-orient: vertical;
          overflow: hidden;
        }

        .book-progress {
          margin-bottom: 20px;

          .progress-bar {
            height: 8px;
            background: var(--border-color);
            border-radius: 4px;
            overflow: hidden;
            margin-bottom: 8px;

            .progress-fill {
              height: 100%;
              background: linear-gradient(90deg, var(--primary-color), var(--primary-light));
              transition: width 0.3s ease;
            }
          }

          .progress-text {
            font-size: 14px;
            color: var(--text-secondary);
            font-weight: 500;
          }
        }

        .book-actions {
          display: flex;
          flex-direction: column;
          gap: 12px;
          margin-top: auto;

          .btn {
            width: 100%;

            &:disabled {
              opacity: 0.6;
              cursor: not-allowed;
              transform: none !important;
            }
          }
        }
      }
    }
  }
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

@media (max-width: 768px) {
  .books-page {
    padding: 20px 0;

    .header {
      flex-direction: column;
      align-items: stretch;
      text-align: center;

      .title {
        font-size: 1.5rem;
      }

      .actions {
        justify-content: center;
      }
    }

    .books-grid {
      grid-template-columns: 1fr;
    }
  }
}
</style>
